<template>
  <div class="user">
    <basic-container>
      <avue-crud
        ref="crud"
        :option="option"
        v-model="form"
        :page="page"
        :table-loading="listLoading"
        :before-open="handleOpenBefore"
        :data="list"
        @on-load="getList"
        @search-change="handleFilter"
        @refresh-change="handleRefreshChange"
        @row-update="update"
        @search-reset="searchReset"
        @row-save="create">
        <template
          slot="username"
          slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
        <template
          slot="role"
          slot-scope="scope">
          <span
            v-for="(role,index) in scope.row.roleList"
            :key="index">
            <el-tag>{{ role.roleName }} </el-tag>&nbsp;&nbsp;
          </span>
        </template>
        <template
          slot="deptId"
          slot-scope="scope">
          {{ scope.row.deptName }}
        </template>
        <template
          slot="lockFlag"
          slot-scope="scope">
          <el-tag>{{ scope.label }}</el-tag>
        </template>
        <template
          slot="roleForm"
          slot-scope="scope">
          <avue-select
            v-model="role"
            :dic="rolesOptions"
            :props="roleProps"
            placeholder="请选择角色"/>
        </template>
	<template slot="deviceOperateNoForm" slot-scope="scope">
              <el-select v-model="form.deviceOperateNo" placeholder="请选择">
                <el-option
                  v-for="item in deviceList"
                  :key="item.operationCode"
                  :label="item.operationCode"
                  :value="item.operationCode"
                >
                </el-option>
              </el-select>
        </template>
	 <template slot="menuLeft">
              <el-button
                class="filter-item"
                type="primary"
                size="mini"                
                @click="editPWD"
                v-if="sys_user_updatebatch_password || sys_user_edit"
                >批量初始密码
              </el-button>	   
	      <el-button
                class="filter-item"
                type="primary"
                size="mini"               
                @click="editEnable('0')"
                v-if="sys_user_updatebatch_lockflag || sys_user_edit"
                >批量启用用户
              </el-button>
	      <el-button
                class="filter-item"
                type="primary"
                size="mini"              
                @click="editEnable('9')"
                v-if="sys_user_updatebatch_lockflag || sys_user_edit"
                >批量锁定用户
              </el-button>	     
	      <el-button
                class="filter-item"
                type="primary"
                size="mini"              
                @click="editEnable('8')"
                v-if="sys_user_updatebatch_lockflag || sys_user_edit"
                >批量禁用用户
              </el-button>
            </template>
	<!-- <template slot='menuLeft'>
            <el-upload
                  class="upload-inline"
                  action=""
                  :show-file-list="false"
                  accept=".xls,.xlsx"
                  :http-request="handleImport"
                  >
                  <el-button type="primary" size="small">导入</el-button>
          </el-upload>
        </template>-->
      </avue-crud>
    </basic-container>
  </div>

</template>

<script>
    import {addObj, delObj, fetchList, putObj,saveBatch,updateBatch,updateBatchLock, getUserDeviceNoByCondition} from '@/api/admin/user'
    import {deptRoleList} from '@/api/admin/role'
    import {tableOption} from '@/const/crud/admin/userSC'  
    import {store} from '@/store'
    import {mapGetters} from 'vuex'

    export default {
        name: 'SysUserSC',
        data() {
            return {
                searchForm: {},
                option: tableOption,
                roleProps: {
                    label: 'roleName',
                    value: 'roleId'
                },
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20, // 每页显示多少条,
                    isAsc: false// 是否倒序
                },
                list: [],
                listLoading: true,
                role: [],
                form: {},
                rolesOptions: []
            }
        },
        computed: {
            ...mapGetters(['permissions'])
        },
        watch: {
            role() {
                this.form.role = this.role ? [this.role] : []
            }
          },
        created() {
            this.sys_user_add = this.permissions['sys_user_add'];
            this.sys_user_edit = this.permissions['sys_user_edit'];
            this.sys_user_del = this.permissions['sys_user_del'];	    
	    const that = this;
	    const lineCode =this.$store.getters.userInfo.lineCode;
            const stationCode = this.$store.getters.userInfo.stationCode;  
	    if (lineCode && stationCode) {
		getUserDeviceNoByCondition(lineCode, stationCode).then(res => {
		  if (res && res.data.data.records.length) {
		    that.deviceList = res.data.data.records;		   
		  }
		});
	      }

        },
        methods: {
            getList(page, params) {
                this.listLoading = true
                return fetchList(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize
                }, params, this.searchForm)).then(response => {
                    this.list = response.data.data.records
                    this.page.total = response.data.data.total
                    this.listLoading = false
                })
            },
            handleFilter(param, done) {
                this.searchForm = param
                this.getList(this.page, param).then(() => {
                  done()
                })
						},
						handleImport(item){
              let file = item.file
              let param = new FormData()
              param.append('file',file)
              saveBatch(param).then(() => {
                this.$notify({
                  title: '成功',
                  message: '导入成功',
                  type: 'success',
                  duration: 2000
                })
                this.getList(this.page)
              })
            },
            handleRefreshChange() {
                this.getList(this.page)
            },
            handleCreate() {
                this.$refs.crud.rowAdd()
            },
            handleOpenBefore(show, type) {
                window.boxType = type
                if (['edit', 'views'].includes(type)) {
                    for (var i = 0; i < this.form.roleList.length; i++) {
                        this.role = this.form.roleList[i].roleId
                        this.form.role = [this.role]
                    }
                } else if (type === 'add') {
                    this.role = null
                }
                deptRoleList().then(response => {
                    this.rolesOptions = response.data.data;
                    const roles =  this.rolesOptions.filter(w => w.roleCode== 'KYZBY' || w.roleCode=='ZBZZ' || w.roleCode=='ZHANWURENYUAN' || w.roleCode=='CZZZ');
                    this.rolesOptions = roles
                })
                show()
            },
            handleUpdate(row, index) {
                console.log(row)
                this.$refs.crud.rowEdit(row, index)
                this.form.password = undefined
            },
            create(row, done, loading) {
                // if (this.form.phone.indexOf('*') > 0) {
                //     this.form.phone = undefined
                // }
                delete this.form.dates1;
                addObj(this.form).then(() => {
                    this.getList(this.page)
                    done()
                    this.$notify({
                        title: '成功',
                        message: '创建成功',
                        type: 'success',
                        duration: 2000
                    })
                }).catch(() => {
                    loading()
                })
            },
	     //变更启动、禁用 、锁定   flag ：  8 禁用  0：启用
	    editEnable(flag){     
	      if (this.$refs.crud.tableSelect.length < 1) {
		this.$message.error("请选择数据");
		return false;
	      }
	      let tipValue ="禁用";
	      if(flag == '0'){
		  tipValue = "启用";
	      }
	      if(flag == '9'){
		  tipValue = "锁定";
	      }
	      let ids = [];
	      for (const table of this.$refs.crud.tableSelect) {
		ids.push(table.userId);
	      }
	      if(ids==null || ids.length==0 ){
		return;
	      }
	      this.$confirm("确认"+tipValue+"?", "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning"
	      }).then(() => {
		 let str = ids.join(','); // 使用逗号作为分隔符
		 updateBatchLock(str,flag)
		  .then(data => {
		    this.$message.success(tipValue+"成功");
		    done();
		  })
		  .catch(() => {
		    loading();
		  });
		  this.getList(this.page);
	      });
	    },
	    editPWD: function() {
	      if (this.$refs.crud.tableSelect.length < 1) {
		this.$message.error("请选择数据");
		return false;
	      }
	      let ids = [];
	      for (const table of this.$refs.crud.tableSelect) {
		ids.push(table.userId);
	      }      
	      if(ids==null || ids.length==0 ){
		return;
	      }
	      this.$confirm("确认修改?", "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning"
	      }).then(() => {
		let str = ids.join(','); // 使用逗号作为分隔符
		updateBatch(str)
		  .then(data => {
		    this.$message.success("修改成功");
		    done();
		  })
		  .catch(() => {
		    loading();
		  });
		 this.getList(this.page);
	      });
	    },
            update(row, index, done, loading) {
                // if (this.form.phone && this.form.phone.indexOf('*') > 0) {
                //     this.form.phone = undefined
                // }
                delete this.form.dates1;
                putObj(this.form).then(() => {
                    this.getList(this.page)
                    done()
                    this.$notify({
                        title: '成功',
                        message: '修改成功',
                        type: 'success',
                        duration: 2000
                    })
                }).catch(() => {
                    loading()
                })
            },
            searchReset(form){
              for(let key of Object.keys(form)){
                if(this.validatenull(form[key])){
                  delete form[key]
                }
              }
              this.searchForm = form
              this.page.currentPage = 1
              this.getList(this.page);
            },
            deletes(row, index) {
                this.$confirm(
                    '此操作将永久删除该用户(用户名:' + row.username + '), 是否继续?',
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(() => {
                    delObj(row.userId)
                        .then(() => {
                            this.list.splice(index, 1)
                            this.$notify({
                                title: '成功',
                                message: '删除成功',
                                type: 'success',
                                duration: 2000
                            })
                        })
                        .cache(() => {
                            this.$notify({
                                title: '失败',
                                message: '删除失败',
                                type: 'error',
                                duration: 2000
                            })
                        })
                })
            }
        }
    }
</script>
<style lang="scss">
  .user {
    height: 100%;

    &__tree {
      padding-top: 3px;
      padding-right: 20px;
    }

    &__main {
      .el-card__body {
        padding-top: 0;
      }
    }
  }
</style>
